package com.le.tester.imooc.oldfairy;

import java.util.ArrayList;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * createTime：2021/9/1 14:41
 * description：等待全部得线程完成了阶段性的工作，然后再继续执行任务
 */
public class CyclicBarrierTest {
    CyclicBarrier barrier;
    int page = 0;

    public CyclicBarrierTest() {
        barrier = new CyclicBarrier(2, () -> {
            System.out.println("sync...");
            page++;
        });
    }

    void prepareProducts() {
        while (page < 1000) {
            try {
                System.out.println("fetch product...");
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    void prepareDeliverOrders() {
        while (page < 1000) {
            try {
                System.out.println("fetch delivery order...");
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    void run() {
        new Thread(this::prepareProducts).start();
        new Thread(this::prepareDeliverOrders).start();

    }

    public static void main(String[] args) {
        new CyclicBarrierTest().run();
    }
}
